package com.flywen.utils;

import com.flywen.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

public class AESUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtils.class);
    private static final String ALGORITHM_AES = "AES";

    public AESUtils() {
    }

    public static String encryptBase64DecorateAES(String content, String strKey) {
        byte[] encryptAES = encrypt(content, strKey);
        String base64DecorateAESStr = Base64Utils.encryptBase64(encryptAES);
        return base64DecorateAESStr;
    }

    private static byte[] encrypt(String content, String strKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(1, key);
            byte[] result = cipher.doFinal(byteContent);
            return result;
        } catch (Exception var6) {
            LOGGER.error("use AES algorithm encrypt error", var6);
            throw new AppException("9000", "aes encript fail");
        }
    }

    public static String decryptBase64DecorateAES(String content, String secretSeed) {
        return new String(decrypt(Base64Utils.decryptBase64(content.getBytes()), secretSeed));
    }

    public static String decryptBase64DecorateAESWithUTF8(String content, String secretSeed) {
        try {
            return new String(decrypt(Base64Utils.decryptBase64(content.getBytes()), secretSeed), "UTF-8");
        } catch (UnsupportedEncodingException var3) {
            throw new AppException("9999", "decryptBase64DecorateAESWithUTF8 fail");
        }
    }

    private static byte[] decrypt(byte[] content, String strKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception var5) {
            LOGGER.error("use AES algorithm decrypt error", var5);
            throw new AppException("9000", "aes decrypt fail");
        }
    }

    public static void main(String[] args) {
        String aes = encryptBase64DecorateAES("xupan", "er34er5434523123");
        System.out.println(aes);
        System.out.println(decryptBase64DecorateAES(aes, "er34er5434523123"));
    }
}